#include "stdafx.h"
#include "MyLogger.h"
#include "boost/date_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/filesystem.hpp"

using namespace boost::filesystem;

MyLogger::MyLogger( const string& name,const string& pattern,const string& file,bool console ) 
: m_pttern(pattern)
{
	m_logger = Logger::getInstance(name);
	m_logger.setLogLevel(ALL_LOG_LEVEL);

	if (console)
	{
		m_layoutConsole.reset(new PatternLayout(m_pttern));   

		SharedAppenderPtr _append(new My_ConsoleAppender());    
		_append->setLayout( m_layoutConsole );		
		m_logger.addAppender(_append);   
	}
	if (file.c_str())
	{
		path _path = current_path();
		_path /= "/Log/";		
		_path /= LOG_DIR;
		std::string strTime = boost::gregorian::to_iso_string(boost::gregorian::day_clock::local_day());  
		_path /= strTime;

		boost::system::error_code error;

		if (!boost::filesystem::exists(_path))
		{
			boost::filesystem::create_directories(_path,error);
		}
		_path /= file;

		m_layoutFile.reset(new PatternLayout(m_pttern));   

		SharedAppenderPtr _append(new FileAppender(_path.string(),std::ios_base::out | std::ios_base::app));    
		_append->setLayout( m_layoutFile );		
		m_logger.addAppender(_append);   
	}
}
MyLogger* g_netLog;
MyLogger* g_commonLog;
void Initlogger()
{
	MY_ASSERT(g_netLog == NULL,"",return;);

	g_netLog = new  MyLogger("NETLOG","[%-5p]-%-15D{%m/%d/%y %H:%M:%S} : %m\n","Net.log",true);
	g_commonLog = new MyLogger("COMONLOG","[%-5p]-%-15D{%m/%d/%y %H:%M:%S} : %m\n","Common.log",true); 
}

void CleanUplogger()
{
	SAFE_DELETE(g_netLog);
	SAFE_DELETE(g_commonLog);
}

void MyLogger::My_ConsoleAppender::append( const spi::InternalLoggingEvent& event )
{
#ifdef Platfrom_WIN
	HANDLE hConsole = GetStdHandle( STD_OUTPUT_HANDLE);
	if (hConsole)
	{
		Auto_locker lock(m_setcolorCritical);
		if (event.getLogLevel() == ERROR_LOG_LEVEL)
		{
			SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
		}
		else if(event.getLogLevel() == WARN_LOG_LEVEL)
		{
			SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN |FOREGROUND_INTENSITY);
		}
		else if(event.getLogLevel() == INFO_LOG_LEVEL)
		{
			SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN |FOREGROUND_BLUE);
		}
	}
#endif // Platfrom_WIN
	ConsoleAppender::append(event);
}
